package com.wn.service;

import com.alibaba.fastjson.JSON;
import com.common.entity.SensitiveWord;
import com.common.util.sysmgr.SensitiveWordInit;

import com.common.util.sysmgr.SensitivewordEngine;
import com.wn.mapper.SensitiveWordMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service("sensitiveWordService")
@Transactional(rollbackFor = Exception.class)
public class SensitiveWordService {
    @Resource
    private SensitiveWordMapper sensitiveWordMapper;

    @Autowired
    RedisServiceImpl redisService;

    @SuppressWarnings("rawtypes")
    public Set<String> sensitiveWordFiltering(String text)
    {
        if (StringUtils.isEmpty(redisService.get("sensitiveWord"))) {
            // 初始化敏感词库对象
            SensitiveWordInit sensitiveWordInit = new SensitiveWordInit();
            // 从数据库中获取敏感词对象集合（调用的方法来自Dao层，此方法是service层的实现类）
            List<SensitiveWord> sensitiveWords = sensitiveWordMapper.getSensitiveWordListAll();
            // 构建敏感词库
            Map sensitiveWordMap = sensitiveWordInit.initKeyWord(sensitiveWords);
            // 传入SensitivewordEngine类中的敏感词库
            String sensitiveWord = JSON.toJSONString(sensitiveWordMap);

            redisService.set("sensitiveWord", sensitiveWord);
        }
        Object sensitiveWord = JSON.parse((String) redisService.get("sensitiveWord"));

        SensitivewordEngine.sensitiveWordMap =(Map) sensitiveWord;
        // 得到敏感词有哪些，传入2表示获取所有敏感词
        Set<String> set = SensitivewordEngine.getSensitiveWord(text, 2);
        return set;
    }

}
